package com.ptbuy.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.provider.OpenableColumns;

public class MyFileUtils {
    /**
     * Uri转换位真实路径
     * @param context
     * @param uri
     * @return
     */
    public static String getPathFromUri(Context context, Uri uri) {
        if (uri == null) {
            return null;
        }

        if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) {
            return uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
            String authority = uri.getAuthority();

            if (authority.startsWith("com.android.externalstorage")) {
                return Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + uri.getPath().split(":")[1];
            } else {
                String id = DocumentsContract.getDocumentId(uri);
                String[] split = id.split(":");
                if (id.startsWith("raw:")) {
                    return id.replaceFirst("raw:", "");
                }
                String idStr = id;
                if (authority.startsWith("com.android.providers")) {
                    if (split.length > 1) {
                        idStr = split[1];
                    }
                }

                ContentResolver contentResolver = context.getContentResolver();
                Cursor cursor = contentResolver.query(MediaStore.Files.getContentUri("external"),
                        new String[]{MediaStore.Files.FileColumns.DATA},
                        "_id=?",
                        new String[]{idStr}, null);
                if (cursor != null) {
                    cursor.moveToFirst();
                    try {
                        int idx = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);

                        return cursor.getString(idx);
                    } catch (Exception e) {
                    } finally {
                        cursor.close();
                    }
                }
            }
        }
        return null;
    }


    // 辅助方法：获取文件名
    public static String getFileName(Context context, Uri uri) {
        Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
        cursor.moveToFirst();
        int index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
        String name = cursor.getString(index);
        cursor.close();
        return name;
    }
}
